package com.example.business.utils;

import com.google.zxing.WriterException;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class QrCodeUtil {

    // 二维码样式
    public enum DrawStyle {
        SQUARE, CIRCLE
    }

    // 生成Base64格式的二维码
    public static String generateQrCodeBase64(String content, int width, int height, Color foreColor, DrawStyle style) throws WriterException, IOException {
        // 1. 生成二维码矩阵
        QRCode qrCode = Encoder.encode(content, ErrorCorrectionLevel.M);
        ByteMatrix matrix = qrCode.getMatrix();

        // 2. 绘制二维码图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.WHITE); // 背景色
        g2.fillRect(0, 0, width, height);
        g2.setColor(foreColor); // 前景色

        // 计算每个矩阵点的大小
        int cellSize = Math.min(width / matrix.getWidth(), height / matrix.getHeight());
        int offsetX = (width - matrix.getWidth() * cellSize) / 2;
        int offsetY = (height - matrix.getHeight() * cellSize) / 2;

        // 绘制矩阵点（根据样式绘制方形或圆形）
        for (int x = 0; x < matrix.getWidth(); x++) {
            for (int y = 0; y < matrix.getHeight(); y++) {
                if (matrix.get(x, y) == 0) continue; // 0表示白色（背景），跳过

                int drawX = offsetX + x * cellSize;
                int drawY = offsetY + y * cellSize;

                if (style == DrawStyle.CIRCLE) {
                    g2.fillOval(drawX, drawY, cellSize, cellSize); // 圆形点
                } else {
                    g2.fillRect(drawX, drawY, cellSize, cellSize); // 方形点
                }
            }
        }
        g2.dispose();

        // 3. 转换为Base64
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }
}